package com.example.task;

import com.example.constants.Constants;
import com.example.mapper.HistoryDataMapper;
import com.example.pojo.DataInfo;
import com.example.pojo.DeviceAttribute;
import com.example.service.DeviceService;
import com.example.utils.Authentication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
public class DataTask {
    @Autowired
    private HistoryDataMapper historyDataMapper;

    @Autowired
    private DeviceService deviceService;

    /**
     * 每五秒获取一次数据
     */
    @Scheduled(cron = "0/5 * * * * ?", zone = "Asia/Shanghai")
    public void getData() throws Exception {
        log.info("开始执行每五秒获取一次数据");
        // 获取数据
        DeviceAttribute attribute = deviceService.getAttribute(Authentication.getToken());
        //封装数据
        DataInfo dataInfo = DataInfo.builder()
                .deviceId(Constants.DEVICE_ID)
                .temperature(attribute.getTemperature())
                .humidity(attribute.getHumidity())
                .createTime(LocalDateTime.now())
                .build();
        //插入数据
        historyDataMapper.insertData(dataInfo);
        log.info("每五秒获取一次数据执行完毕");
    }

    /**
     *每小时定时聚合温度数据
     */
    @Scheduled(cron = "0 0 * * * ?", zone = "Asia/Shanghai")
    public void aggregationDataByHour(){
        log.info("开始执行每小时定时聚合温度数据");
        historyDataMapper.aggregationDataByHour();
        log.info("每小时定时聚合温度数据执行完毕");
    }

    /**
     *每天定时聚合温度数据
     */
    @Scheduled(cron = "0 0 10 * * ?", zone = "Asia/Shanghai")
    public void aggregationDataByDay(){
        log.info("开始执行每天定时聚合温度数据");
        historyDataMapper.aggregationDataByDay();
        log.info("每天定时聚合温度数据执行完毕");
    }

    /**
     *每月定时聚合温度数据
     */
    @Scheduled(cron = "0 0 10 1 * ?", zone = "Asia/Shanghai")
    public void aggregationDataByMonth(){
        log.info("开始执行每月定时聚合温度数据");
        historyDataMapper.aggregationDataByMonth();
        log.info("每月定时聚合温度数据执行完毕");
    }

}
